package com.befiv.lock.config;

import com.befiv.lock.annotation.Lock;
import com.befiv.lock.redis.RedisLocker;
import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * @Author: Gjq
 * @Date: 2019/6/28 0028 上午 9:44
 */
public class LockMethodInterceptor implements MethodInterceptor {
    @Autowired
    private RedisLocker distributedLocker;

    @Override
    public Object invoke(MethodInvocation methodInvocation) throws Throwable {
        Object lock1 = null;
        Lock lock = methodInvocation.getMethod().getAnnotation(Lock.class);
        if(lock!=null){
            lock1 = distributedLocker.lock(lock.value(), () -> {
                try {
                    return methodInvocation.proceed();
                } catch (Throwable throwable) {
                    throwable.printStackTrace();
                    return null;
                }
            }, lock.expire(), lock.timeout());
        }
        return lock1;
    }
}
